package com.zh.juc.cas;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @Author: zhanghuan
 * @date: 2022/10/18 21:23
 * @description: create it
 * CAS缺点
 * 循环时间长开销大
 * 引出ABA问题
 * 解决方法：AtomicStampedReference
 */
@NoArgsConstructor
@AllArgsConstructor
@Data
class Book {
    private int id;
    private String bookName;
}

public class ABADemo01 {


    public static void main(String[] args) {

        Book java = new Book(1, "java");
        AtomicStampedReference<Book> stampedReference = new AtomicStampedReference<>(java, 1);
        System.out.println(stampedReference.getReference() + "\t" + stampedReference.getStamp());
        Book mysql = new Book(2, "mysql");

        boolean b;
        b = stampedReference.compareAndSet(java, mysql, stampedReference.getStamp(), stampedReference.getStamp() + 1);
        System.out.println(b + "\t" + stampedReference.getReference() + "\t" + stampedReference.getStamp());

        b = stampedReference.compareAndSet(mysql, java, stampedReference.getStamp(), stampedReference.getStamp() + 1);
        System.out.println(b + "\t" + stampedReference.getReference() + "\t" + stampedReference.getStamp());


    }
}
